package com.newmuis.open.codeeval.easy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * CodeEval.com > Easy Challenges > Bit Positions
 * 
 * Description:
 * 
 * Given a number n and two integers p1,p2 determine if the bits in position p1 and p2 are the same
 * or not. Positions p1,p2 and 1 based.
 * 
 * Input sample:
 * 
 * The first argument will be a text file containing a comma separated list of 3 integers, one list
 * per line. e.g.
 * 
 * 86,2,3
 * 125,1,2
 * 
 * Output sample:
 * 
 * Print to stdout, 'true'(lowercase) if the bits are the same, else 'false'(lowercase).
 * e.g.
 * 
 * true
 * false
 * 
 * @author Jonathan Newmuis (jon@newmuis.com)
 * @category easy
 * 
 */
public class position {
	/**
	 * Determines whether the bits in positions {@code p1} and {@code p2} are the same in the binary
	 * representation of the integer {@code n}.
	 * 
	 * @param n
	 * @param p1
	 * @param p2
	 * @return true if and only if the bits at positions {@code p1} and {@code p2} of {@code n} are
	 *         the same.
	 */
	private static boolean checkBitPositions(final int n, final int p1, final int p2) {
		return ((n << (32 - p1) >> 31) ^ (n << (32 - p2) >> 31)) == 0;
	}

	/**
	 * @param args should contain only one CLI argument: the path to an input file which specifies
	 *            the input in the defined format.
	 * @throws IOException if there is a problem reading the given input file.
	 */
	public static void main(final String[] args) throws IOException {
		// Verify input argument length.
		if (args.length < 1) {
			throw new RuntimeException("Must specify input file path.");
		} else if (args.length > 1) {
			throw new RuntimeException("Illegal input arguments specified.");
		}

		// Read file from specified path.
		final BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
		String line;

		while ((line = reader.readLine()) != null) {
			// Parse the arguments.
			final String[] positionArgs = line.split(",");

			// Verify the length of the "position" arguments given in the input file.
			if (positionArgs.length != 3) {
				throw new RuntimeException("Input file must contain three arguments per line.");
			}

			try {
				// Determine whether the bits at p1 and p2 are the same.
				final int n = Integer.parseInt(positionArgs[0]);
				final int p1 = Integer.parseInt(positionArgs[1]);
				final int p2 = Integer.parseInt(positionArgs[2]);
				System.out.println(checkBitPositions(n, p1, p2));
			} catch (final NumberFormatException e) {
				throw new RuntimeException("Input file contained non-numeric arguments.");
			}
		}
	}

}
